<template>
  <div class="ketangneirongguanlishu">
    <div class="tree">
      <!-- <div class="header">
                <p>序号</p>
                <p>名称</p>
                <p>课件</p>
                <p>操作</p>
            </div> -->
      <div class="content">
        <div class="comp-tree">
          <el-button
            class="comp-tr-top"
            type="primary"
            size="small"
            @click="handleAddTop"
            >+添加章节</el-button
          >
          <!-- tree -->
          <el-tree
            ref="SlotTree"
            :data="setTree"
            :props="defaultProps"
            :expand-on-click-node="false"
            highlight-current
            :node-key="NODE_KEY"
            icon-class="el-icon-circle-plus-outline"
          >
            <div class="comp-tr-node" slot-scope="{ node, data }">
              <!-- 编辑状态 -->
              <template v-if="node.isEdit">
                <el-input
                  v-model="data.name"
                  autofocus
                  size="mini"
                  :ref="'slotTreeInput' + data[NODE_KEY]"
                  @blur.stop="handleInput(node, data)"
                  @keyup.enter.native="handleInput(node, data)"
                ></el-input>
              </template>

              <!-- 非编辑状态 -->
              <template v-else>
                <!-- 名称： 新增节点增加class（is-new） -->
                <span
                  :class="[
                    data[NODE_KEY] < NODE_ID_START ? 'is-new' : '',
                    'comp-tr-node--name',
                  ]"
                >
                  {{ node.label }}
                </span>

                <!-- 按钮 -->
                <span class="comp-tr-node--btns">
                  <!-- 新增 -->
                  <el-button
                    icon="el-icon-plus"
                    size="mini"
                    type="primary"
                    @click="handleAdd(node, data)"
                    >新增</el-button
                  >

                  <!-- 编辑 -->
                  <el-button
                    icon="el-icon-edit"
                    size="mini"
                    type="info"
                    @click="handleEdit(node, data)"
                    >编辑</el-button
                  >

                  <!-- 删除 -->
                  <el-button
                    icon="el-icon-delete"
                    size="mini"
                    type="danger"
                    @click="handleDelete(node, data)"
                    >删除</el-button
                  >
                  <!-- 上传 -->
                  <!-- <el-button v-show="node.level == 2"
                            icon="el-icon-upload"
                            size="mini"
                            circle
                            type="warning"
                            @click="handleUpload(node, data)"
                            >上传</el-button> -->
                  <!-- 是否上传了 -->
                  <a-button
                    type="link"
                    v-show="data.file_name"
                    @click="editPPT(data)"
                  >
                    {{ data.file_name }}
                  </a-button>
                  <!-- 上传 -->
                  <a-upload
                    v-show="node.level == 2"
                    name="file"
                    :multiple="false"
                    @change="changeFile"
                    :customRequest="customRequest"
                  >
                    <!-- <a-button type="primary" circle> <a-icon type="upload" />上传</a-button> -->
                    <a-button
                      type="primary"
                      icon="upload"
                      @click="deliverKey(data)"
                    ></a-button>
                  </a-upload>
                  <el-link
                    v-show="false"
                    type="primary"
                    @click="handleUpload(node, data)"
                    >{{ data.file_name }}</el-link
                  >
                  <!-- <a href="javascript:;">asdf</a>  -->
                </span>
              </template>
            </div>
          </el-tree>
        </div>
      </div>
    </div>

    <a-modal
      v-model="modalVisible"
      title="上传中，请稍后"
      centered
      @ok="() => (modalVisible = false)"
    >
      <img src="/imgs/loading.gif" alt="" />
    </a-modal>
  </div>
</template>

<script>
import { Button } from 'element-ui'
import { Tree } from 'element-ui'
import { Input } from 'element-ui'
export default {
  name: 'ketangneirongguanlishu',
  components: {
    [Button.name]: Button,
    [Tree.name]: Tree,
    [Input.name]: Input,
  },
  data() {
    return {
      treelist: [
        {
          id: 1,
          name: '北京市',
          ProSort: 1,
          isEdit: false,
          children: [
            {
              id: 35,
              name: '朝阳区',
              isEdit: false,
              children: [],
            },
            {
              id: 36,
              name: '海淀区',
              isEdit: false,
              children: [],
            },
            {
              id: 37,
              name: '房山区',
              isEdit: false,
              children: [],
            },
            {
              id: 38,
              name: '丰台区',
              isEdit: false,
              children: [],
            },
            {
              id: 39,
              name: '昌平区',
              isEdit: false,
              children: [],
            },
            {
              id: 40,
              name: '大兴区',
              isEdit: false,
              children: [],
            },
          ],
        },
        {
          id: 2,
          name: '天津市',
          ProSort: 2,
          isEdit: false,
          children: [
            {
              id: 41,
              name: '北辰区',
              isEdit: false,
              children: [],
            },
            {
              id: 42,
              name: '河北区',
              isEdit: false,
              children: [],
            },
            {
              id: 43,
              name: '西青区',
              isEdit: false,
              children: [],
            },
            {
              id: 44,
              name: '东丽区',
              isEdit: false,
              children: [],
            },
          ],
        },
      ],
      headers: {
        authorization: 'authorization-text',
      },
      modalVisible: false,
      key: 0,
      isLoading: false, // 是否加载
      setTree: [], // tree数据
      NODE_KEY: 'id', // id对应字段
      MAX_LEVEL: 2, // 设定最大层级
      NODE_ID_START: 0, // 新增节点id，逐次递减
      startId: null,
      defaultProps: {
        // 默认设置
        children: 'children',
        label: 'name',
      },
      initParam: {
        // 新增参数
        name: '新增节点',
        pid: 0,
        children: [],
      },
    }
  },
  mounted() {
    this.getTreeList()
    // this.setTree = this.treelist || []
  },
  // updated() {
  //     this.axios.defaults.headers.common['Authorization'] = window.sessionStorage.getItem('token')
  //     this.axios.post('/course/query_all/').then((res)=>{
  //         console.log(res)
  //         this.setTree = res || []
  //     })
  // },
  created() {
    // 初始值
    this.startId = this.NODE_ID_START
  },
  methods: {
    // 获得树列表
    getTreeList() {
      this.axios.defaults.headers.common[
        'Authorization'
      ] = window.sessionStorage.getItem('token')
      this.axios.post('/course/query_all/').then(res => {
        console.log(res)
        this.setTree = res || []
      })
    },
    handleDelete(_node, _data) {
      // 删除节点
      console.log(_node, _data)
      // 判断是否存在子节点
      if (_data.children && _data.children.length !== 0) {
        this.$message.error('此节点有子级，不可删除！')
        return false
      } else {
        // 判断此节点为章节节点
        if (_node.level == 1) {
          // 删除操作
          let DeletOprate = () => {
            this.$nextTick(() => {
              if (this.$refs.SlotTree) {
                this.axios
                  .post('/course/delete_chapter/', {
                    key: _data.key,
                  })
                  .then(() => {
                    this.$refs.SlotTree.remove(_data)
                    this.$message.success('删除成功！')
                  })
              }
            })
          }

          // 二次确认
          let ConfirmFun = () => {
            this.$confirm('是否删除此节点？', '提示', {
              confirmButtonText: '确认',
              cancelButtonText: '取消',
              type: 'warning',
            })
              .then(() => {
                DeletOprate()
              })
              .catch(() => {})
          }

          // 判断是否新增： 新增节点直接删除，已存在的节点要二次确认
          _data[this.NODE_KEY] < this.NODE_ID_START
            ? DeletOprate()
            : ConfirmFun()
        } else {
          //否则此节点为小节节点
          // 删除操作
          let DeletOprate = () => {
            this.$nextTick(() => {
              if (this.$refs.SlotTree) {
                this.axios
                  .post('/course/delete_section/', {
                    key: _data.key,
                  })
                  .then(() => {
                    this.$refs.SlotTree.remove(_data)
                    this.$message.success('删除成功！')
                  })
              }
            })
          }

          // 二次确认
          let ConfirmFun = () => {
            this.$confirm('是否删除此节点？', '提示', {
              confirmButtonText: '确认',
              cancelButtonText: '取消',
              type: 'warning',
            })
              .then(() => {
                DeletOprate()
              })
              .catch(() => {})
          }

          // 判断是否新增： 新增节点直接删除，已存在的节点要二次确认
          _data[this.NODE_KEY] < this.NODE_ID_START
            ? DeletOprate()
            : ConfirmFun()
        }
      }
    },
    handleInput(_node, _data) {
      // 修改节点
      // 判断是否为章
      if (_node.level == 1) {
        this.axios
          .post('/course/modify_chapter/', {
            key: _data.key,
            name: _data.name,
          })
          .then(() => {})
        this.$message.success('修改成功！')
      } else {
        this.axios
          .post('/course/modify_section/', {
            key: _data.key,
            name: _data.name,
          })
          .then(() => {})
        this.$message.success('修改成功！')
      }
      // this.$message.success("修改成功！");
      console.log(_data.name)
      console.log(this.setTree)
      // 退出编辑状态
      if (_node.isEdit) {
        this.$set(_node, 'isEdit', false)
      }
    },
    handleEdit(_node, _data) {
      // 编辑节点
      console.log(_node, _data)
      // 设置编辑状态
      if (!_node.isEdit) {
        this.$set(_node, 'isEdit', true)
      }

      // 输入框聚焦
      this.$nextTick(() => {
        if (this.$refs['slotTreeInput' + _data[this.NODE_KEY]]) {
          this.$refs['slotTreeInput' + _data[this.NODE_KEY]].$refs.input.focus()
        }
      })
    },
    handleAdd(_node, _data) {
      // 新增节点
      console.log(_node, _data)
      // 判断层级
      if (_node.level >= this.MAX_LEVEL) {
        this.$message.warning('当前已达到' + this.MAX_LEVEL + '级，无法新增！')
        return false
      }

      // 参数修改
      let obj = JSON.parse(JSON.stringify(this.initParam)) // copy参数
      obj.pid = _data[this.NODE_KEY] // 父id
      obj[this.NODE_KEY] = --this.startId // 节点id：逐次递减id
      // 判断字段是否存在
      if (!_data.children) {
        this.$set(_data, 'children', [])
      }
      // 新增数据
      _data.children.push(obj)

      // 展开节点
      if (!_node.expanded) {
        _node.expanded = true
      }
      console.log(_data.ProSort)
      this.axios
        .post('/course/add_section/', {
          name: obj.name,
          chapter_key: _data.key,
        })
        .then(() => {
          this.$message.success('新增成功')
          this.getTreeList()
        })
    },
    handleAddTop() {
      // 添加顶部节点
      let obj = JSON.parse(JSON.stringify(this.initParam)) // copy参数
      obj[this.NODE_KEY] = --this.startId // 节点id：逐次递减id
      this.setTree.push(obj)
      console.log(obj)
      this.axios
        .post('/course/add_chapter/', {
          name: obj.name,
        })
        .then(() => {
          this.getTreeList()
        })
    },
    handleUpload(_node, _data) {
      // 处理上传
      console.log(_node)
      console.log(_data)
    },
    changeFile(info) {
      // 上传文件
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        this.$message.success(`${info.file.name} 上传成功`)
      } else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} 上传失败.`)
      }
    },
    customRequest(data) {
      // 上传提交
      const formData = new FormData()
      formData.append('file', data.file)
      formData.append('key', this.key)
      console.log(data)
      // console.log('_data'+_data)
      this.modalVisible = true
      this.saveFile(formData)
    },
    deliverKey(data) {
      this.key = data.key
      console.log(this.key)
    },
    saveFile(formData) {
      this.axios({
        method: 'post',
        url: '/course/add_sectionfile/',
        headers: {},
        params: {},
        data: formData,
      })
        .then(response => {
          console.log(response)
          this.modalVisible = false
          this.$message.success('上传成功！')
          this.getTreeList()
        })
        .catch(function(error) {
          console.log(error)
        })
    },
    // 编辑PPT
    editPPT(data) {
      this.$store.dispatch('savaChapterData', data)
      this.$router.push('/manage/ketangneirongguanli/kejianbianji')
    },
  },
}
</script>

<style lang="scss">
.ketangneirongguanlishu {
  background-color: #fff;
  img {
    width: 100px;
    height: 100px;
  }
  .tree {
    // .header{
    //     display: flex;
    //     justify-content: space-between;
    //     margin-left: 30px;
    //     background-color: skyblue;
    //     width: 1100px;
    //     height: 53px;
    //     line-height: 53px;
    //     font-size: 18px;
    //     p{
    //         padding: 0 30px;
    //     }
    // }
    a {
      margin-left: 50px;
    }
    .content {
      .el-tree-node__content {
        display: flex;
        align-items: center;
        height: 75px;
        cursor: pointer;
        border-bottom: 1px solid #ccc;
      }
      .el-tree-node__expand-icon {
        cursor: pointer;
        color: #c0c4cc;
        font-size: 24px;
        transform: rotate(0);
        transition: transform 0.3s ease-in-out;
        &.is-leaf {
          color: transparent;
        }
      }
      .ant-btn-icon-only {
        width: 32px;
        height: 32px;
        padding: 0;
        font-size: 16px;
        border-radius: 16px;
        margin-left: 10px;
      }
      .ant-btn-link {
        color: #1890ff;
        background-color: transparent;
        border-color: transparent;
        box-shadow: none;
        margin-left: 50px;
      }
      .ant-upload-list {
        display: none;
      }
      /* common */

      // 显示按钮
      .show-btns {
        opacity: 1;
      }

      /* common end */

      .comp-tree {
        width: 100%;
        max-width: 1150px;
        max-height: 80vh;
        padding: 2em;
        overflow: auto;
        // 顶部按钮
        .comp-tr-top {
          width: 100px;
          margin-bottom: 2em;
        }
        // 自定义节点
        .comp-tr-node {
          width: 100%;
          height: 100%;
          font-size: 25px;
          // label
          .comp-tr-node--name {
            display: inline-block;
            line-height: 75px;
            min-height: 75px;
            margin-left: 30px;
            // 新增
            &.is-new {
              font-weight: normal;
            }
          }
          // button
          .comp-tr-node--btns {
            line-height: 75px;
            margin-left: 50px;
            opacity: 0;
            transition: opacity 0.1s;
            .el-button {
              transform: scale(1); // 缩小按钮
              & + .el-button {
                margin-left: 10px;
              }
            }
            .el-link {
              margin-left: 100px;
            }
          }
        }
        // 高亮显示按钮
        .is-current {
          & > .el-tree-node__content {
            .comp-tr-node--btns {
              @extend .show-btns;
            }
          }
        }
        // 悬浮显示按钮
        .el-tree-node__content {
          &:hover {
            .comp-tr-node--btns {
              @extend .show-btns;
            }
          }
        }
      }
    }
  }
}
</style>
